import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { apiGetHotelInfo } from '@/api/admin-api';

// Define proper types for hotel information
interface HotelInfo {
  id: string;
  name: string;
  address: string;
  phone: string;
  city: string;
  desc: string;
  logo?: string;
  photos?: string[] | string;
  [key: string]: any; // For any additional properties
}

export const useHotelStore = defineStore('hotel', () => {
  const hasHotel = ref(false);
  const hotelId = ref<string>('');
  const hotelInfo = ref<HotelInfo | null>(null);
  const isLoading = ref(false);
  const isInitialized = ref(false);
  
  // 添加一个标志来跟踪是否正在进行初始化
  const isInitializing = ref(false);
  
  // 添加一个Promise来跟踪初始化过程
  let initializationPromise: Promise<HotelInfo | null> | null = null;
  
  // Computed property to ensure hotelId is always available
  const safeHotelId = computed(() => {
    return hotelId.value || (hotelInfo.value?.id || '');
  });
  
  function setHasHotel(val: boolean) {
    hasHotel.value = val;
  }
  
  function setHotelId(id: string) {
    hotelId.value = id;
    // 同步更新hotelInfo
    if (id && hotelInfo.value) {
      hotelInfo.value.id = id;
    }
  }
  
  function setHotelInfo(info: HotelInfo) {
    hotelInfo.value = info;
    // 同步更新hotelId和hasHotel状态
    if (info && info.id) {
      hotelId.value = info.id;
      hasHotel.value = true;
    } else {
      hasHotel.value = false;
    }
  }

  async function getHotelInfo() {
    // 如果已经在加载中，返回现有的Promise
    if (isInitializing.value && initializationPromise) {
      console.log("hotelStore已经在初始化中，返回现有Promise");
      return initializationPromise;
    }
    
    // 如果已经加载完成且有数据，直接返回
    if (isInitialized.value && hotelInfo.value && hotelInfo.value.id) {
      console.log("hotelStore已初始化，直接返回现有数据");
      return Promise.resolve(hotelInfo.value);
    }
    
    // 开始新的加载过程
    isInitializing.value = true;
    isLoading.value = true;
    
    // 创建新的Promise
    initializationPromise = new Promise<HotelInfo | null>(async (resolve) => {
      try {
        console.log("开始获取酒店信息...");
        const res = await apiGetHotelInfo();
        
        if (res && res.data) {
          hotelInfo.value = res.data;
          if (hotelInfo.value && hotelInfo.value.id) {
            hotelId.value = hotelInfo.value.id;
            hasHotel.value = true;
            console.log("获取到酒店ID:", hotelId.value);
          } else {
            hasHotel.value = false;
            console.warn("酒店信息中没有id字段");
          }
          isInitialized.value = true;
          resolve(hotelInfo.value);
        } else {
          hasHotel.value = false;
          console.warn("获取酒店信息失败: 响应数据格式不正确", res);
          resolve(null);
        }
      } catch (error) {
        hasHotel.value = false;
        console.error('获取酒店信息失败:', error);
        resolve(null);
      } finally {
        isLoading.value = false;
        isInitializing.value = false;
      }
    });
    
    return initializationPromise;
  }

  // 初始化时自动获取酒店信息
  // 注意：这会在首次使用store时触发，而不是每次使用时
  if (!isInitialized.value && !hotelInfo.value && !isInitializing.value) {
    console.log("初始化hotelStore，开始获取酒店信息");
    getHotelInfo().catch(err => {
      console.error("初始化获取酒店信息失败:", err);
    });
  }
  
  return { 
    hasHotel, 
    hotelId,
    safeHotelId, // Always returns a valid ID if available
    hotelInfo,
    isLoading,
    isInitialized,
    isInitializing,
    setHasHotel, 
    setHotelId, 
    setHotelInfo,
    getHotelInfo
  };
}); 